package com.education.cms.web;

import com.education.cms.common.ResultModle;
import com.education.cms.domain.Clock;
import com.education.cms.dto.clock.ComplexSearchDto;
import com.education.cms.service.ClockService;
import com.education.cms.utils.RedisUtils;
import com.education.cms.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
public class ClockController {
    @Autowired
    private ClockService clockService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private UserUtils userUtils;

    /**
     * 打卡功能（包含上下课
     */
    @GetMapping("clock")
    public ResultModle clock(HttpServletRequest request){
        String ticket= (String) request.getSession().getAttribute("loginfo");
        String[] userInfo = redisUtils.get(ticket).split("-");
        Integer userId = Integer.parseInt(userInfo[0]);
        Clock clock = clockService.getMyClock(userId);
        if (clock == null){  //此时上课打卡
            clockService.clockIn(userId);
            return ResultModle.ok("上课打卡成功！");
        }else
            {  //此时下课打卡
            return ResultModle.ok(clockService.clockOut(clock));
        }
    }

    /**
     * 登陆用户的打卡分页列表
     */
    @PostMapping("myClockList/{page}")
    public ResultModle getClockListByUser(@PathVariable("page")int page, HttpServletRequest request){
        Integer userId = userUtils.getUserId(request);
        Pageable pageable = PageRequest.of(page-1,5, Sort.Direction.DESC,"clockId");
        Page<Clock> myClock = clockService.getMyClockList(userId,pageable);
        return ResultModle.ok(myClock);
    }

    /**
     * 根据用户id、日期区间及打卡状态查询打卡列表（管理员权限
     */
    @PostMapping("clockList/{page}")
    public ResultModle complexSearch(@PathVariable("page")int page, @RequestBody ComplexSearchDto searchDto){
        Pageable pageable = PageRequest.of(page-1,5);
        Page<Clock> clocks = clockService.getClockList(searchDto,pageable);
        return ResultModle.ok(clocks);
    }
}
